﻿using Api.Core.Common.Attributes;
using Api.Core.Common.Cache;
using AspectCore.DynamicProxy;
using AspectCore.Injector;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Core.AOP
{
    //支持参数缓存，异步缓存
    public class CacheAop : BaseAop
    {
        [FromContainer]
        private IRedisCache _redisCache { get; set; }

        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var method = context.ProxyMethod ?? context.ServiceMethod;

            if (method.ReturnType == typeof(void))
            {
                await next.Invoke(context);
                return;
            }
            var attribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CacheAttribute)) as CacheAttribute;

            if (attribute == null)
            {
                await next.Invoke(context);
                return;
            }
            try
            {
                Console.WriteLine("Before CacheAop call");
                var cacheKey = CacheKey.GetCacheKey(context.ServiceMethod, context.Parameters);
                var cacheValue = _redisCache.GetValue(cacheKey);
                if (string.IsNullOrWhiteSpace(cacheValue))
                {
                    var result = await RunAndGetReturn(context, next);
                    _redisCache.Set(cacheKey, result, TimeSpan.FromMinutes(attribute.ExpirationMinutes));
                    return;
                }
                else
                {
                    Type returnType;
                    if (typeof(Task).IsAssignableFrom(method.ReturnType))
                    {
                        returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault();
                    }
                    else
                    {
                        returnType = method.ReturnType;
                    }
                    dynamic _result = JsonConvert.DeserializeObject(cacheValue, returnType);
                    context.ReturnValue = typeof(Task).IsAssignableFrom(method.ReturnType) ? Task.FromResult(_result) : _result;
                    return;
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Catch CacheAop call");
                throw;
            }
            finally
            {
                Console.WriteLine("After CacheAop call");
            }
        }
    }
}
